package com.abc.core.service.impl;

import com.abc.core.consts.CodeDefConst;
import com.abc.core.consts.OperationFlag;
import com.abc.core.def.Dna;
import com.abc.core.dm.InstDmService;
import com.abc.core.instance.bo.Cell;
import com.abc.core.instance.bo.Inst;
import com.abc.core.service.DnaCacheService;
import com.abc.core.service.InstService;
import com.abc.core.tool.DnaTool;
import com.abc.core.util.InstVisitor;

public class InstServiceImpl implements InstService {

    private DnaCacheService dnaCacheService;

    private InstDmService instDmService;

    @Override
    public Inst initInst(String dnaCode) {
        Dna dna = this.dnaCacheService.getDna(dnaCode);
        Inst inst = new Inst(dnaCode, dna.getDnaName());
        inst.setDna(dna);
        Cell cell = DnaTool.dna2Cell(CodeDefConst.INST_TYPE_DEFAULT, dna);
        inst.addCell(cell);
        return inst;
    }

    @Override
    public Inst saveInst(Inst inst) {
        InstVisitor.visitInst(inst, (Inst localInst) -> {
            if (localInst.getDna() == null) {
                Dna dna = dnaCacheService.getDna(localInst.getDnaCode());
                localInst.setDna(dna);
            }
        });

        return instDmService.saveInst(inst);
    }

    @Override
    public Inst getInst(String dnaCode, Object cellKey) {
        Dna dna = this.dnaCacheService.getDna(dnaCode);
        if (dna == null) {
            throw new RuntimeException("找不到 dna: " + dnaCode);
        }
        Inst inst = this.instDmService.getInst(dna, cellKey);
        if (inst != null) {
            InstVisitor.visitInst(inst, (Inst localInst) -> {
                for (Cell cell : localInst.getCells()) {
                    cell.setOperationFlag(OperationFlag.OPERATION_FLAG_UNCHANGED);
                }
            });
        }

        return inst;
    }

    @Override
    public Object deleteInst(String dnaCode, Object cellKey) {
        Dna dna = this.dnaCacheService.getDna(dnaCode);
        this.instDmService.deleteInst(dna, cellKey);
        return cellKey;
    }
}
